package com.djf.djfcs.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.djf.djfcs.entity.Product;
import com.djf.djfcs.service.IProductService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商品管理控制器
 * 提供商品的CRUD操作接口
 */
@Slf4j
@RestController
@RequestMapping("/api/products")
@Api(tags = "商品管理")
public class ProductController {

    @Autowired
    private IProductService productService;

    /**
     * 创建商品
     */
    @PostMapping
    @ApiOperation("创建商品")
    public ResponseEntity<Map<String, Object>> createProduct(@Valid @RequestBody Product product) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean save = productService.save(product);
            result.put("success", true);
            result.put("message", "商品创建成功");
            result.put("data", save);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("创建商品失败", e);
            result.put("success", false);
            result.put("message", "商品创建失败：" + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 根据ID查询商品
     */
    @GetMapping("/{id}")
    @ApiOperation("根据ID查询商品")
    public ResponseEntity<Map<String, Object>> getProductById(
            @ApiParam("商品ID") @PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        try {
            Product product = productService.getById(id);
            if (product != null) {
                result.put("success", true);
                result.put("data", product);
            } else {
                result.put("success", false);
                result.put("message", "商品不存在");
            }
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("查询商品失败，ID：{}", id, e);
            result.put("success", false);
            result.put("message", "查询商品失败：" + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 根据商品编码查询商品
     */
    @GetMapping("/code/{productCode}")
    @ApiOperation("根据商品编码查询商品")
    public ResponseEntity<Map<String, Object>> getProductByCode(
            @ApiParam("商品编码") @PathVariable String productCode) {
        Map<String, Object> result = new HashMap<>();
        try {
            Product product = productService.getProductByCode(productCode);
            if (product != null) {
                result.put("success", true);
                result.put("data", product);
            } else {
                result.put("success", false);
                result.put("message", "商品不存在");
            }
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("查询商品失败，商品编码：{}", productCode, e);
            result.put("success", false);
            result.put("message", "查询商品失败：" + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 更新商品
     */
    @PutMapping("/{id}")
    @ApiOperation("更新商品")
    public ResponseEntity<Map<String, Object>> updateProduct(
            @ApiParam("商品ID") @PathVariable Long id,
            @Valid @RequestBody Product product) {
        Map<String, Object> result = new HashMap<>();
        try {
            product.setId(id);
            boolean b = productService.updateById(product);
            result.put("success", true);
            result.put("message", "商品更新成功");
            result.put("data", b);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("更新商品失败，ID：{}", id, e);
            result.put("success", false);
            result.put("message", "商品更新失败：" + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 删除商品
     */
    @DeleteMapping("/{id}")
    @ApiOperation("删除商品")
    public ResponseEntity<Map<String, Object>> deleteProduct(
            @ApiParam("商品ID") @PathVariable Long id) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = productService.removeById(id);
            result.put("success", success);
            result.put("message", success ? "商品删除成功" : "商品删除失败");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("删除商品失败，ID：{}", id, e);
            result.put("success", false);
            result.put("message", "商品删除失败：" + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 分页查询商品
     */
    @GetMapping
    @ApiOperation("分页查询商品")
    public ResponseEntity<Map<String, Object>> getProductPage(
            @ApiParam("页码") @RequestParam(defaultValue = "1") int pageNum,
            @ApiParam("页大小") @RequestParam(defaultValue = "10") int pageSize,
            @ApiParam("商品名称") @RequestParam(required = false) String productName,
            @ApiParam("商品分类") @RequestParam(required = false) String category,
            @ApiParam("商品品牌") @RequestParam(required = false) String brand,
            @ApiParam("商品状态") @RequestParam(required = false) String status) {
        Map<String, Object> result = new HashMap<>();
        try {
            IPage<Product> page = productService.getProductPage(pageNum, pageSize, 
                    productName, category, brand, status);
            result.put("success", true);
            result.put("data", page);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("分页查询商品失败", e);
            result.put("success", false);
            result.put("message", "查询商品失败：" + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 根据分类查询商品
     */
    @GetMapping("/category/{category}")
    @ApiOperation("根据分类查询商品")
    public ResponseEntity<Map<String, Object>> getProductsByCategory(
            @ApiParam("商品分类") @PathVariable String category) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<Product> products = productService.getProductsByCategory(category);
            result.put("success", true);
            result.put("data", products);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("根据分类查询商品失败，分类：{}", category, e);
            result.put("success", false);
            result.put("message", "查询商品失败：" + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 根据品牌查询商品
     */
    @GetMapping("/brand/{brand}")
    @ApiOperation("根据品牌查询商品")
    public ResponseEntity<Map<String, Object>> getProductsByBrand(
            @ApiParam("商品品牌") @PathVariable String brand) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<Product> products = productService.getProductsByBrand(brand);
            result.put("success", true);
            result.put("data", products);
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("根据品牌查询商品失败，品牌：{}", brand, e);
            result.put("success", false);
            result.put("message", "查询商品失败：" + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 更新商品库存
     */
    @PutMapping("/{id}/stock")
    @ApiOperation("更新商品库存")
    public ResponseEntity<Map<String, Object>> updateProductStock(
            @ApiParam("商品ID") @PathVariable Long id,
            @ApiParam("库存数量") @RequestParam Integer stock) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = productService.updateProductStock(id, stock);
            result.put("success", success);
            result.put("message", success ? "库存更新成功" : "库存更新失败");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("更新商品库存失败，ID：{}，库存：{}", id, stock, e);
            result.put("success", false);
            result.put("message", "库存更新失败：" + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }

    /**
     * 更新商品状态
     */
    @PutMapping("/{id}/status")
    @ApiOperation("更新商品状态")
    public ResponseEntity<Map<String, Object>> updateProductStatus(
            @ApiParam("商品ID") @PathVariable Long id,
            @ApiParam("商品状态") @RequestParam String status) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = productService.updateProductStatus(id, status);
            result.put("success", success);
            result.put("message", success ? "状态更新成功" : "状态更新失败");
            return ResponseEntity.ok(result);
        } catch (Exception e) {
            log.error("更新商品状态失败，ID：{}，状态：{}", id, status, e);
            result.put("success", false);
            result.put("message", "状态更新失败：" + e.getMessage());
            return ResponseEntity.badRequest().body(result);
        }
    }
}